package com.cxs.service.impl;

import com.cxs.ex.BusinessException;
import com.cxs.service.BucketService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.RemoveBucketArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author: cxs
 */
@Service
public class BucketServiceImpl implements BucketService {

    @Autowired
    private MinioClient minioClient;

    @Override
    public void createBucket(String bucketName) {
        Boolean flag = existBucket(bucketName);
        if (flag) {
            throw new BusinessException("该空间已经存在");
        }
        try {
            minioClient.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(bucketName)
                            .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean existBucket(String bucketName) {
        boolean flag = false;
        try {
            flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    /**
     * removeBucket不会删除存储桶里的对象，你需要通过removeObject API来删除文件
     *
     * @param bucketName
     */
    @Override
    public void removeBucket(String bucketName) {
        Boolean flag = existBucket(bucketName);
        if (!flag) {
            throw new BusinessException("该空间不存在");
        }
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
